package com.smart.web;

import com.smart.domain.User;
import com.smart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;

@RestController
public class LoginController {

    @Autowired
    private Optional<UserService> userService;

    @RequestMapping(value = "/index.html")
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
        if (userService.isPresent()) {
            boolean isValidUser = userService.get().hasMatchUser(loginCommand.getUserName(),
                    loginCommand.getPassword());
            if (!isValidUser) {
                return new ModelAndView("login", "error", "用户名或密码错误。");
            } else {
                User user = userService.get().findUserByUserName(loginCommand
                        .getUserName());
                user.setLastIp(request.getLocalAddr());
                user.setLastVisit(new Date());
                userService.get().loginSuccess(user);
                request.getSession().setAttribute("user", user);
                return new ModelAndView("main");
            }
        } else {
            return new ModelAndView("login", "error", "注入失败！");
        }
    }


}
